package com.ruoyi.project.module.packet.controller;

import com.alibaba.fastjson.JSONObject;
import com.arronlong.httpclientutil.HttpClientUtil;
import com.arronlong.httpclientutil.common.HttpConfig;
import com.arronlong.httpclientutil.common.HttpHeader;
import com.arronlong.httpclientutil.exception.HttpProcessException;
import com.ruoyi.common.utils.MD5Util;
import com.ruoyi.common.utils.PropertiesFileUtil;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.constant.BusinessType;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.framework.web.page.TableDataInfo;
import com.ruoyi.project.module.packet.domain.Packet;
import com.ruoyi.project.module.packet.service.IPacketService;
import com.ruoyi.project.module.packetConfig.domain.PacketConfig;
import com.ruoyi.project.module.packetConfig.service.IPacketConfigService;
import com.ruoyi.project.system.config.service.IConfigService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.http.Header;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * 母红包 信息操作处理
 * 
 * @author ruoyi
 * @date 2018-08-04
 */
@Controller
@RequestMapping("/module/packet")
@Api(value = "红包记录--Web", description = "红包记录--Web")
public class PacketController extends BaseController
{
    private String prefix = "module/packet";

	@Autowired
	private IPacketService packetService;

	@Autowired
	private IPacketConfigService packetConfigService;

	@Autowired
	private IConfigService configService;

	@RequiresPermissions("module:packet:view")
	@GetMapping()
	public String packet()
	{
	    return prefix + "/packet";
	}
	
	/**
	 * 查询母红包列表
	 */
	@RequiresPermissions("module:packet:list")
	@PostMapping("/list")
	@ResponseBody
	public TableDataInfo list(Packet packet)
	{
		startPage();
        List<Packet> list = packetService.selectPacketList(packet);
		return getDataTable(list);
	}
	
	/**
	 * 新增母红包
	 */
	@GetMapping("/add")
	public String add()
	{
	    return prefix + "/add";
	}



	/**
	 * 新增母红包
	 */
	@GetMapping("/addNormal")
	public String addNormal()
	{
		return prefix + "/addNormal";
	}

	@RequiresPermissions("module:packet:addRedPacketNormal")
	@ApiOperation(value = "创建红包----发私人红包",notes = "创建私人红包") //系统模拟发私人红包
	@RequestMapping(value = "/addRedPacketNormal", method = RequestMethod.POST)
	@ResponseBody
	public AjaxResult addRedPacketNormal(Packet packet , @RequestParam(required = true) String number ) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("redPacketId", packet.getRedPacketId());
		BigDecimal redPacketAdmount = packet.getRedPacketAdmount();
		if(redPacketAdmount!=null){
			map.put("redPacketAdmount", redPacketAdmount.toString());
		}
		map.put("redPacketRemark", packet.getRedPacketRemark());
		map.put("redPacketPic", packet.getRedPacketPic());
		Integer redPacketQuantity=packet.getRedPacketQuantity();
		if(redPacketQuantity!=null){
			map.put("redPacketQuantity", redPacketQuantity.toString());
		}
		map.put("redPacketType", packet.getRedPacketType());
		map.put("redPacketPw", packet.getRedPacketPw());
		BigDecimal redPacketLon = packet.getRedPacketLon();
		if(redPacketLon!=null){
			map.put("redPacketLon", redPacketLon.toString());
		}
		BigDecimal redPacketLat = packet.getRedPacketLon();
		if(redPacketLat!=null){
			map.put("redPacketLat", redPacketLat.toString());
		}
		map.put("randomRules", packet.getRandomRules());
		map.put("advertisingExternalLink", packet.getAdvertisingExternalLink());
		map.put("advertisingPhone", packet.getAdvertisingPhone());
		map.put("advertisingAddress", packet.getAdvertisingAddress());
		map.put("redPacketUserId", packet.getRedPacketUserId());
		map.put("redPacketStatus", packet.getRedPacketStatus());
		map.put("redPacketSonArea", packet.getRedPacketSonArea());
		map.put("userImg", packet.getUserImg());
		map.put("number", number);
		/*CheckSignUtil.formatUrlMap(map);
		map.put("key", PropertiesFileUtil.getInstance("CheckSignKey").get("APP"));
		if (!CheckSignUtil.formatUrlMap(map).equals(sign)) {
			logger.error("验签失败");
			return error("签名验证失败");
		} else {
			logger.info("验签成功");
		}*/
		String remoteServer_base_url = PropertiesFileUtil.getInstance("remoteServer").get("base_url");

		String url = remoteServer_base_url+"redPacket/addwebRedPacketNormal";
		String random= UUID.randomUUID().toString();
		String key = PropertiesFileUtil.getInstance("CheckSignKey").get("APP").toUpperCase();
		String randomSign= MD5Util.MD5(random.concat("&").concat(key));

		String dataSign = MD5Util.MD5(random.concat(number).concat(redPacketAdmount.toString()).concat(redPacketQuantity.toString()));
		Header[] headers 	= HttpHeader.custom()
				.userAgent("Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36")
				.other("random", random)
				.other("randomSign", randomSign)
				.other("dataSign", dataSign)
				.other("authorization", "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx")
				.build();


		HttpConfig config = HttpConfig.custom()
				.headers(headers)	//设置headers，不需要时则无需设置
				.url(url)					//设置请求的url
				.map(map)			//设置请求参数，没有则无需设置
				.encoding("utf-8") //设置请求和返回编码，默认就是Charset.defaultCharset()
				;
		String reponse_result = null;
		try {
			reponse_result = HttpClientUtil.post(config);
		} catch (HttpProcessException e) {
			e.printStackTrace();
		}
		JSONObject resjsStr = JSONObject.parseObject(reponse_result);
		String msg=resjsStr.getString("msg");
		Integer code=Integer.parseInt(resjsStr.getString("code"));
		if(code.equals(0)){
			return success(msg);
		}
		return error(msg);
	}





	/**
	 * 新增保存母红包
	 */
	@RequiresPermissions("module:packet:add")
	@Log(title = "母红包", action = BusinessType.INSERT)
	@PostMapping("/add")
	@ResponseBody
	public AjaxResult addSave(Packet packet)
	{		
		return toAjax(packetService.insertPacket(packet));
	}

	/**
	 * 修改母红包
	 */
	@GetMapping("/edit/{redPacketId}")
	public String edit(@PathVariable("redPacketId") String redPacketId, ModelMap mmap)
	{
		Packet packet = packetService.selectPacketById(redPacketId);
		mmap.put("packet", packet);
	    return prefix + "/edit";
	}
	
	/**
	 * 修改保存母红包
	 */
	@RequiresPermissions("module:packet:edit")
	@Log(title = "母红包", action = BusinessType.UPDATE)
	@PostMapping("/edit")
	@ResponseBody
	public AjaxResult editSave(Packet packet)
	{		
		return toAjax(packetService.updatePacket(packet));
	}
	
	/**
	 * 删除母红包
	 */
	@RequiresPermissions("module:packet:remove")
	@Log(title = "母红包", action = BusinessType.DELETE)
	@PostMapping( "/remove")
	@ResponseBody
	public AjaxResult remove(String ids)
	{		
		return toAjax(packetService.deletePacketByIds(ids));
	}


}
